package com.newtouch.xcd.admin.aop;

import com.newtouch.xcd.common.to.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

@Slf4j
@Aspect
@Component
public class DataVaildAspect {

    /**
     * 目标方法的异常，一般都需要再次抛出去。让别人感知
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.newtouch.xcd.admin..*Controller.*(..))")
    public Object validAround(ProceedingJoinPoint point) throws Throwable {
        Object proceed = null;

        log.debug("校验切面介入工作....");
        Object[] args = point.getArgs();
        for (Object obj:args){
            if(obj instanceof BindingResult){
                BindingResult r = (BindingResult) obj;
                if(r.getErrorCount()>0){
                    //框架自动校验检测到错了
                    return new CommonResult().validateFailed(r);
                };
            }
        }
        //就是我们反射的  method.invoke();
        proceed = point.proceed(point.getArgs());
        log.debug("校验切面将目标方法已经放行....{}",proceed);

        return proceed;
    }

}
